package main

import (
	"context"
	"crypto/tls"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"time"

	"gitee.com/general252/proxy_device/pd_client"
	"gitee.com/general252/proxy_device/pd_device"
	"gitee.com/general252/proxy_device/pd_server"
)

const (
	HttpPort   = 9443
	Socks5Port = 9080

	DeviceID = "device_id_xyz"
)

func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)

	go func() {
		time.Sleep(time.Second)

		// 上线一个设备
		deviceDemo()
	}()

	go func() {
		time.Sleep(time.Second * 3)

		clientDemo()
	}()

	s := pd_server.NewServer(HttpPort, Socks5Port)
	s.Serve()
}

func deviceDemo() {
	url := fmt.Sprintf("ws://127.0.0.1:%v/api/v1/device/%v", HttpPort, DeviceID)

	d := pd_device.NewDevice(url)
	if err := d.Connect(); err != nil {
		log.Println(err)
	}
}

func clientDemo() {
	// socks5代理客户端
	pxy, err := pd_client.NewSocks5ProxyClient(DeviceID, "tcp", fmt.Sprintf("127.0.0.1:%v", Socks5Port))
	if err != nil {
		log.Println(err)
		return
	}

	cli := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
			DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
				return pxy.Dial(network, addr)
			},
		},
	}

	var sendRequest = func(name string, cli *http.Client) {
		url := "https://www.baidu.com/s?wd=Rust"
		req, _ := http.NewRequest(http.MethodGet, url, nil)
		reply, err := cli.Do(req)
		if err != nil {
			log.Println(name, err)
			return
		}

		data, err := io.ReadAll(reply.Body)
		if err != nil {
			log.Println(name, err)
			return
		}

		log.Println(name, string(data))
	}

	sendRequest("test baidu", cli)

}
